package com.shopping.controller;

import com.shopping.bean.Cart;
import com.shopping.bean.User;
import com.shopping.service.ICartService;
import com.shopping.service.impl.CartService;
import com.shopping.util.LayData;
import com.shopping.util.SYS;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("cart")
public class CartController {
    @Autowired
ICartService cartService;

    //添加商品到购物车
    @RequestMapping("add")
    @ResponseBody
    public LayData add(HttpSession session ,Cart cart){
        User loginUser=(User)session.getAttribute(SYS.SHOPPING_LOGIN_USER);
        System.out.println(loginUser);
        System.out.println(cart);
        cart.setUserid(loginUser.getUserid());

        return LayData.success(cartService.addCart(cart));
    }

    @RequestMapping("getCart")
    @ResponseBody
    public LayData getCart(HttpSession session,Cart cart){
        return LayData.success(cartService.addCart(cart));
    }

    @RequestMapping("getCarts")
    @ResponseBody
    public LayData getCarts(HttpSession session){
        User loginUser=(User) session.getAttribute(SYS.SHOPPING_LOGIN_USER);
        int userid=loginUser.getUserid();
        List<Cart> list=cartService.getCarts(userid);
        return LayData.success(list);
    }

    @RequestMapping("edit")
    @ResponseBody
    public LayData edit(HttpSession session, @RequestParam Integer productid, @RequestParam Integer number) {
        User user = (User) session.getAttribute(SYS.SHOPPING_LOGIN_USER);
        if (user == null) return LayData.success("请先登录");

        Cart cart = new Cart();
        cart.setUserid(user.getUserid());
        cart.setProductid(productid);
        cart.setQuantity(number);

        try {
            Cart updatedCart = cartService.editCart(cart);
            return LayData.success("数量更新成功", updatedCart.getQuantity());
        } catch (RuntimeException e) {
            return LayData.success(e.getMessage());
        }
    }

    @RequestMapping("delete")
    @ResponseBody
    public  LayData delete(HttpSession session,Cart cart){
        User loginUser=(User) session.getAttribute(SYS.SHOPPING_LOGIN_USER);
        cart.setUserid(loginUser.getUserid());
        return  LayData.success(cartService.deleteCart(cart));
    }

}
